package com.yxp.offer;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther : yxpweb
 * @Date : 2021/8/21 8:35
 * @Description: 动态规划 剑指 Offer 42. 连续子数组的最大和
 */
public class Problem42 {

    public static void main(String[] args) {
        Problem42 problem42 = new Problem42();
        int[] nums = new int[]{-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(problem42.maxSubArray(nums));
    }

    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        int res = dp[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
            res = Math.max(res, dp[i]);
        }
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < dp.length; i++) {
            list.add(dp[i]);
        }
        System.out.println(list);
        return res;
    }
}
